package com.lune.blog.base.sentinel;


import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lune.blog.base.result.CommonResult;
import com.lune.blog.base.result.ResultCode;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yanjizhw@163.com
 * @date 2021/10/31 20:11
 * 描述: 从sentinel-dashboard 控制台添加的限流规则，触发流控后，会在这里执行代码
 * @since 1.0.0
 */
@Component
public class SpBlockHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
//        AjaxJson aj = AjaxJson.get(503, "系统繁忙，请稍后再试");
        CommonResult<Object> aj = CommonResult.failed(ResultCode.TOO_MANY_REQUEST, "系统繁忙，请稍后再试");
        // http说明，我要返回JSON对象
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().print(new ObjectMapper().writeValueAsString(aj));
    }

}
